const ArticleModel = require('../model/article')
const dayjs = require('dayjs')

module.exports = {
  async index(ctx, next) {
    // 获取文章数据
    const pageSize = 5
    const currentPage = Number(ctx.query.page) || 1

    let cid; // 类型

    const query = cid ? { category: cid} : {}
    const allArticleCount = await ArticleModel.find(query).count()
    const pageCount = Math.ceil(allArticleCount / pageSize)
    const pageStart = currentPage - 2 > 0 ? currentPage - 2 : 1
    const pageEnd = pageStart + 4 >= pageCount ? pageCount : pageStart + 4
    let articles = await ArticleModel.find(query).sort({ _id: -1 }).skip((currentPage - 1) * pageSize).limit(pageSize)
    
    // articles.forEach((item) => {
    //   item.time = dayjs(item.meta.updateAt).format('YYYY/MM/DD')
    // })
    // console.log(articles);
    let pagination = []
    if (pageCount >= 3) {
      if (Number(currentPage) === 1) {
        pagination.push(1, 2, 3)
      } else if (Number(currentPage) === pageCount && pageCount >= 3) {
        pagination.push(Number(currentPage) - 2, Number(currentPage) - 1, Number(currentPage))
      } else if (Number(currentPage) < pageCount && pageCount >= 3) {
        pagination.push(Number(currentPage) - 1, Number(currentPage), Number(currentPage) + 1)
      }
    } else if (pageCount >= 2 && Number(currentPage) < pageCount) {
      pagination.push(Number(currentPage), Number(currentPage) + 1)
    } else {
      pagination.push(currentPage)
    }

    const baseUrl = `${ctx.path}?page=`

    await ctx.render('index', {
      title: '蜗牛-blog',
      articles,
      pageSize,
      currentPage,
      allArticleCount,
      pageCount,
      pageStart,
      pageEnd,
      baseUrl,
      pagination
    })

  }
}